import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Modal, Form, Upload, Button, message, Space } from 'antd'
import PropTypes from 'prop-types'
import { UploadOutlined } from '@ant-design/icons'
import { requestOneFile } from '@js/request'
import { getUploadProps, validateFileRequire } from '@js/tool'
const { Item } = Form
class UploadModal extends Component {
  state = {
    fileList: []
  }

  formRef = React.createRef()

  onFinish (data) {
    const hide = message.loading('上传中', 120)
    const file = data.file ? data.file.fileList : []
    if (file.length === 0) {
      return false
    }
    requestOneFile(file[0])
      .then((res) => {
        res = res.data
        hide()
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        this.props.onChange(res.data.id)
      })
      .catch(() => hide())
  }

  resetFileList () {
    this.setState({
      fileList: []
    })
  }

  componentDidUpdate (prev) {
    if (prev.visible && !this.props.visible) {
      this.resetFileList()
    }
  }

  render () {
    return (
      <Modal
        title='上传笔录'
        open={this.props.visible}
        onCancel={() => this.props.hide()}
        footer={(
          <Space>
            <Button onClick={() => this.props.hide()}>取消</Button>
            <Button type='primary' disabled={this.state.fileList.length === 0} onClick={() => this.formRef.current.submit()}>确定</Button>
          </Space>
        )}
        destroyOnClose
      >
        <Form ref={this.formRef} onFinish={d => this.onFinish(d)}>
          <Item name='file' label='线上签字笔录文件' rules={[{ required: true, message: '线上签字笔录文件不能为空' }, validateFileRequire.bind(this, '线上签字笔录文件不能为空')]}>
            <Upload {...getUploadProps.call(this, this.formRef, '.docx')}>
              <Button disabled={this.state.fileList.length !== 0}>
                <UploadOutlined /> 上传文件
              </Button>
            </Upload>
          </Item>
        </Form>
      </Modal>
    )
  }
}

UploadModal.proptypes = {
  visible: PropTypes.bool,
  onChange: PropTypes.func,
  hide: PropTypes.func
}

UploadModal.defaultProps = {
  visible: false,
  onChange: () => {},
  hide: () => {}
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
  }
})

export default connect(mapState, mapDispatch)(UploadModal)
